require('dotenv').config();

const express = require('express');
const axios = require('axios');
const fileRoutes = require('./routes/fileRoutes')
// 工作流
const workflowRoutes = require('./routes/workflowRoutes')
// 智能体
const botRoutes = require('./routes/botRoutes')

// home
const homeRoutes = require('./routes/homeRoutes')

// 微信小程序登录
const loginRoutes = require('./routes/loginRoutes')

// 用户
const userRoutes = require('./routes/userRoutes')

// 微信公众号
const wechatRoutes = require('./routes/wechatRoutes')

// 游戏路由
const gameRoutes = require('./routes/gameRoutes')

// 壁纸路由
const wallpaperRoutes = require('./routes/wallpaperRoutes')

// coze 对话
const {
	conversationCreate,
	sendCozeChat,
	fetchCozeChatRetrieve,
	fetchCozeChatMessageList,
	sendCozeChatStream
} = require('./modules/coze-chat'); // 引入封装的函数

const {	
	getGQAvatarBot
} = require('./modules/workflow');

const cozeToken = require('./modules/cozeToken');

const app = express();
const port = 7070;

// 解析JSON格式的请求体
app.use(express.json());

// 允许跨域请求
app.use((req, res, next) => {
	res.header('Access-Control-Allow-Origin', '*');
	res.header('Access-Control-Allow-Headers', 'Origin,X-Requested-With,Content-Type,Accept');
	next()
})


// coze 附件功能
app.use('/api/file', fileRoutes)

app.use('/api/workflow', workflowRoutes)

app.use('/api/bot', botRoutes)

app.use('/api/home', homeRoutes)

app.use('/api/login', loginRoutes)

app.use('/api/user', userRoutes)

// 微信公众号路由
app.use('/api/wechat', wechatRoutes)

// 游戏路由
app.use('/api/game', gameRoutes)

// 壁纸路由
app.use('/api/wallpaper', wallpaperRoutes)

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 轮询的异步函数
async function pollUntilDone(chat_id,interval, checkCondition) {
  return new Promise((resolve, reject) => {
    const intervalId = setInterval(async () => {
			try {
				console.log('我来循环了1')
        const response = await fetchCozeChatRetrieve(chat_id);
				if (checkCondition(response.data)) {
					console.log('我查到有消息了', response.data)
					resolve(response.data);
					clearInterval(intervalId);
					
				}
      } catch (error) {
        clearInterval(intervalId);
        reject(error);
      }
    }, interval);
  });
}
// 创建空会话
app.get('/conversation/create', async (req, res) => {
	try {
		const response = await conversationCreate()
		res.json({
			success: true,
			code: 200,
			data: response.data,
			errMsg: '成功'
		})
	} catch (error) {
		res.status(500).send({
			code: 500,
			msg: 'Error',
			success: false
		})
	}
})

// coze对话
app.get('/coze', async(req, res) => {
	try {
		const msg = req.query.msg;
		const response = await sendCozeChat(msg);
		const resulet = await pollUntilDone(response.data.id, 5000, data => { return data.status === 'completed' })
		const message = await fetchCozeChatMessageList(response.data.id)
		res.json({
			success: true,
			code: 200,
			data: message.data,
			errMsg: '成功'
		})
	} catch (error) {
		res.status(500).send({
			code: 500,
			msg: 'Error',
			success: false
		})
	}
})

// coze 流式对话
app.post('/chat-stream', async (req, res) => {
  try {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Transfer-Encoding': 'chunked'
    });
    
    const { msg, conversationId, botId } = req.body;
    console.log('req', req.body);

    const headers = await cozeToken.getAuthHeaders();
    const request = axios.post(
      `https://api.coze.cn/v3/chat?conversation_id=${conversationId}`,
      {
        bot_id: botId,
        user_id: 'yuanlj',
        stream: true,
        auto_save_history: true,
        additional_messages: [
          {
            role: "user",
            content: msg,
            content_type: "text"
          }
        ]
      },
      {
        headers: {
          ...headers,
          'Content-Type': 'application/json'
        },
        responseType: 'stream'
      }
    );

    request.then(response => {
      response.data.on('data', (chunk) => {
        console.log(chunk.toString());
        res.write(`${chunk.toString()}\n\n`);
      });

      response.data.on('end', () => {
        setTimeout(() => {
          res.end();
        }, 3000);
      });

      response.data.on('error', (e) => {
        console.error(`Problem with request: ${e.message}`);
        res.status(500).send('Error occurred');
      });
    });
  } catch (error) {
    console.error('流式对话失败:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

// 国庆头像生成器
app.post('/coze/gqAvatar', async(req, res) => {
	try {
		const { template, avatar  } = req.body
		const response = await getGQAvatarBot(template, avatar );
		res.json({
			success: true,
			code: 200,
			data: response.data,
			errMsg: '成功'
		})
	} catch (error) {
		res.status(500).send({
			code: 500,
			msg: 'Error',
			success: false
		})
	}
})




app.use((err,req,res,next)=>{
	console.error("自定义错误收集器："+err.stack);
});


app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});